package push_log

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	"gorm.io/gorm"
)

type gfyxRadarSubscriptionPushLogRepos struct {
	tenant_db.TenantDB
}

func NewGfyxRadarSubscriptionPushLogRepos() GfyxRadarSubscriptionPushLogReposIface {
	return &gfyxRadarSubscriptionPushLogRepos{}
}

func (r *gfyxRadarSubscriptionPushLogRepos) Create(ctx context.Context, po *GfyxRadarSubscriptionPushLogPo) (*GfyxRadarSubscriptionPushLogPo, error) {
	err := r.GetTenantDB(ctx).Table(po.TableName()).Create(po).Error
	if err != nil {
		return nil, err
	}
	return po, nil
}

func (r *gfyxRadarSubscriptionPushLogRepos) Update(ctx context.Context, where, updates map[string]interface{}) error {
	return r.GetTenantDB(ctx).Table(GfyxRadarSubscriptionPushLogPo{}.TableName()).Where(where).Updates(updates).Error
}

func (r *gfyxRadarSubscriptionPushLogRepos) Query(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (int64, []*GfyxRadarSubscriptionPushLogPo, error) {
	var result []*GfyxRadarSubscriptionPushLogPo
	var count int64
	db := r.GetTenantDB(ctx).Table(GfyxRadarSubscriptionPushLogPo{}.TableName())

	if createdOn, ok := condition["created_on"]; ok {
		db = db.Where("created_on BETWEEN \"" + createdOn.(string) + " 00:00:00\"" + " AND \"" + createdOn.(string) + " 23:59:59\"")
		delete(condition, "created_on")
	}
	db = db.Where(condition)

	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}

	if pageInfo != nil && pageInfo.PageSize > 0 && pageInfo.Page > 0 {
		db = db.Offset((pageInfo.Page - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize)
	}

	err = db.Find(&result).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, result, nil
		}
		return 0, nil, err
	}
	return count, result, nil
}
